from PySide6.QtCore import Qt
from PySide6.QtGui import QKeyEvent
from PySide6.QtWidgets import (
    QLabel,
    QLineEdit,
)


class FocusLockedLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.focus_locked = False
        self.default_style = self.styleSheet()
        self.locked_style = """
            .FocusLockedLineEdit {
                background-color: #fffacd;
                border: 2px solid #ff8c00;
                border-radius: 3px;
                padding: 5px;
                font-weight: bold;
            }
        """

        # 状态标签（用于显示当前状态）
        self.status_label = QLabel("焦点未锁定", self)
        self.status_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.status_label.setStyleSheet(
            "color: #666; font-size: 10pt; margin-right: 5px;"
        )

        # 调整标签位置
        self.textChanged.connect(self._adjust_status_label)

    def _adjust_status_label(self):
        # 确保状态标签始终在右侧可见
        self.status_label.move(self.width() - self.status_label.width() - 5, 2)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._adjust_status_label()

    def setFocusLocked(self, locked: bool):
        self.focus_locked = locked

        if locked:
            self.setStyleSheet(self.locked_style)
            self.status_label.setText("焦点已锁定")
            self.status_label.setStyleSheet(
                "color: #ff0000; font-size: 10pt; font-weight: bold; margin-right: 5px;"
            )
            self.setFocus()  # 立即获取焦点
        else:
            self.setStyleSheet(self.default_style)
            self.status_label.setText("焦点未锁定")
            self.status_label.setStyleSheet(
                "color: #666; font-size: 10pt; margin-right: 5px;"
            )

    def focusOutEvent(self, event):
        if self.focus_locked:
            event.ignore()
            self.setFocus()
        else:
            super().focusOutEvent(event)

    def keyPressEvent(self, event: QKeyEvent):
        # 锁定状态下拦截Tab键和Shift+Tab
        if self.focus_locked and (
            event.key() == Qt.Key_Tab or event.key() == Qt.Key_Backtab
        ):
            return

        super().keyPressEvent(event)

    def mousePressEvent(self, event):
        # 锁定状态下忽略外部点击（但允许内部点击）
        if self.focus_locked and not self.rect().contains(event.pos()):
            event.ignore()
        else:
            super().mousePressEvent(event)
            if self.focus_locked:
                self.setFocus()
